//
//  CDManager.m
//  CoreDataDemo
//
//  Created by chenguibang on 16/2/26.
//  Copyright © 2016年 chenguibang. All rights reserved.
//

#import "CDManager.h"
#import <mach/mach_time.h>
@implementation CDManager

@synthesize managedObjectContext    = _managedObjectContext;
@synthesize managedObjectModel      = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+(CDManager *)shareManager{
    static dispatch_once_t onceToken;
    static  CDManager *share = nil;
    dispatch_once(&onceToken, ^{
        share =  [[self alloc]init];
    });
    return share;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}





/**
 *  受控对象模型
 *
 *  @return
 */
-(NSManagedObjectModel *)managedObjectModel{
    if (!_managedObjectModel) {
        
        NSURL *modelurl = [[NSBundle mainBundle]URLForResource:@"UserModel" withExtension:@"momd"];
        _managedObjectModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelurl];
        
        
    }
    return _managedObjectModel;
}
/**
 *  调度器
 *
 *  @return
 */
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    if (!_persistentStoreCoordinator) {
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:self.managedObjectModel];
        
         NSURL *store =  [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        
        NSURL *storeurl = [store URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",@"UserModel"]];
        NSLog(@"%@",store);
        NSDictionary *option = nil;
        NSError *error = nil;
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeurl options:option error:&error]) {
            
            NSLog(@"未能创建持久化数据调度器 Unresolved error %@, %@", error, [error userInfo]);
            abort();
            
        } 
    }
    
    
    return _persistentStoreCoordinator;
}

/**
 *  创建管理上下文
 *
 *  @return
 */
-(NSManagedObjectContext *)managedObjectContext{
    if (!_managedObjectContext) {
        NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
        if (coordinator!=nil) {
            NSManagedObjectContext *context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
            [context performBlockAndWait:^{
                NSUndoManager *undoManager = [[NSUndoManager alloc] init];
                [undoManager setGroupsByEvent:NO];
                [context setUndoManager:undoManager];
                
                // Set persistent store
                [context setPersistentStoreCoordinator:coordinator];
            }];
            _managedObjectContext = context;
        }
        
      
    }
    return _managedObjectContext;
}

#pragma mark ————管理对象上下文————
- (BOOL)saveContext{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil){
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]){
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            return NO;
        }
    }
    else{
        NSLog(@"Managed Object Context is nil");
        return NO;
    }
    NSLog(@"Context Saved");
    
    return YES;
}



-(NSManagedObject*)entityWithNamed:(NSString*)entityName {
   return  [NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:self.managedObjectContext];
}
-(NSArray *)queryWithEntity:(NSString*)entityName key:(NSString *)key  value:(NSString*)value{
//    CDManager *manager = [CDManager shareManager];
    //初始化一个查询请求
    NSFetchRequest *requst = [[NSFetchRequest alloc]init];
    //设置要查询的实体
    requst.entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    //设置排序 按age降序
//    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
//    requst.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
    NSString *pri = [NSString stringWithFormat:@"%@ == \"%@\"",key,value];
    NSPredicate *prediction = [NSPredicate predicateWithFormat:pri];
    NSLog(@"%@",prediction.description);
    requst.predicate = prediction;
    NSError *error3 = nil;
    //执行请求
    NSArray *objs = [self.managedObjectContext executeFetchRequest:requst error:&error3];
    if (error3) {
        [NSException raise:@"查询错误" format:@"%@", [error3 localizedDescription]];
    }
    return objs;
}

@end
